<?php
/**
 *
 * Copyright 2011 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */


//require '//facebook//src//facebook.php';
$filepath = "facebook/src/facebook.php";
if(file_exists($filepath))
{

	require $filepath;
}
else
{
	echo 'fileNOTfound'.$filepath;
}

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => '200920903268840',
  'secret' => '39adc8315720cbb42b33aba6505a2cd6',
  'cookie' => true,
));

// We may or may not have this data based on a $_GET or $_COOKIE based session.
//
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getSession();
//echo"gogogo";
$me = null;
// Session based API call.
if ($session) {
  try {
    $uid = $facebook->getUser();
    $me = $facebook->api('/me');
	$me2 = $facebook->api('/me/home?limit=100');
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}

//echo"gogogo";
// login or logout url will be needed depending on current user state.
if ($me) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
  $loginUrl = $facebook->getLoginUrl(array(  
    'req_perms' => 'email,offline_access,read_stream,status_update,publish_stream'  
));
}
//echo"gogogo";

// This call will always work since we are fetching public data.
//$naitik = $facebook->api('/naitik');

?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
  <head>
    <title>Sentiment Analysis </title>
    <style>
      body {
        font-family: 'Lucida Grande', Verdana, Arial, sans-serif;
      }
      h1 a {
        text-decoration: none;
        color: #3b5998;
      }
      h1 a:hover {
        text-decoration: underline;
      }
    </style>
  </head>
  <body>
    <!--
      We use the JS SDK to provide a richer user experience. For more info,
      look here: http://github.com/facebook/connect-js
    -->
    <div id="fb-root"></div>
    <script>
      window.fbAsyncInit = function() {
        FB.init({
          appId   : '<?php echo $facebook->getAppId(); ?>',
          session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
          status  : true, // check login status
          cookie  : true, // enable cookies to allow the server to access the session
          xfbml   : true // parse XFBML
        });

        // whenever the user logs in, we refresh the page
        FB.Event.subscribe('auth.login', function() {
          window.location.reload();
        });
      };

      (function() {
        var e = document.createElement('script');
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
      }());
    </script>


    <h1><a href="index.php">Sentiment Analysis &amp; Opinion Mining on Facebook</a></h1>
    
    <h2>So what is sentiment Analysis? </h2>
    <p>Sentiment analysis or opinion mining refers to the application of natural language processing,<br /> computational linguistics, and text analytics to identify and extract subjective information in <br />source materials.
    This is what <a href="http://en.wikipedia.org/wiki/Sentiment_analysis">Wikipedia</a> has to say about it. 
    </p>
	<p>
    I am working on a research project involving analysis of data posted by users on Facebook. <br />The goal of this project is to better understand social interests of a user on Facebook. This <br />understanding would aid in the solution of one of the biggest problems that the e-commerce <br />industry is facing today-How to create more user targeted advertisements on the internet<br />(my project focuses on advertisements appearing on Facebook).
</p>
<br />
<p>
As a part of this project, I need to collect a substantial amount of data. It would be great, if <br />you could contribute to this data collection process. <br />
You just need to login using your facebook account and give permission to my application.

    </p>


    <?php if ($me): ?>
    <a href="<?php echo $logoutUrl; ?>">
      <img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">
    </a>
    <?php else: ?>
    <div>
       <!-- <fb:login-button perms="email,offline_access,read_stream" show-faces="true"></fb:login-button> -->
    </div>
     <div>
      <a href="<?php echo $loginUrl; ?>">
        <img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif">
      </a>
    </div>
    <?php endif ?>

    <!--<h3>Session</h3>-->
    <?php if ($me): ?>
    <pre><?php //print_r($session); ?></pre>

    
    <?php echo $me['name']; ?>

   
    <pre><?php //print_r($me2); ?></pre>
    
    <?php
	    //start accessing the data array
		//Obtain the output file handle
		//Define the 3 parameters
		
		$param_array = array('feed','statuses','home');
		$count = count($param_array);
		while($count > 0)
		{
			$param = $param_array[$count-1];
			$me2 = $facebook->api('/me/'.$param.'?limit=100');
			if($me2)
			{
		
					$outputFile = fopen("outputFiles/".$param."/".$facebook->getUser()."_".$param.".txt","w") or die("Could not open the file.");
		
					$parentArray = array();
					$from = array();
					$actionsOnAPost = array();
					$action = array();
					$likes = array();
					$i = 0;
					$parentArray = $me2['data'];
					//print_r($parentArray);
					foreach($parentArray as $row)
					{
			
							//print_r($initialRow);
							//echo "<br/><br/>";
							$postId = $row['id'];
							print($row['id']);
							$from = $row['from'];
							$message = $row['message'];
							$link = $row['link'];
							$source = $row['source'];
							$nameTitle = $row['name'];
							$caption = $row['caption'];
							$likes = $row['likes'];
							$description = $row['description'];
							$action = $row['actions'];
							$messageType = $row['type'];
							$createdTime = $row['created_time'];
							$updatedTime = $row['updated_time'];
							$comments = $row['comments'];
			
							//output the data to a text file.
			
							fwrite($outputFile,"id\t".$postId."\n");	
							fwrite($outputFile,"message\t".$message."\n");
							fwrite($outputFile,"from\t".$from['name']."\n");
							fwrite($outputFile,"link\t".$link."\n");
							fwrite($outputFile,"Source\t".$source."\n");
							fwrite($outputFile,"nameTitle\t".$nameTitle."\n");
							fwrite($outputFile,"description\t".$description."\n");
							if($comments['count'] > 0)
							{
								fwrite($outputFile,"Comments_Begin\n");
								$comments_data = $comments['data'];
								foreach($comments_data as $row)
								{
									$comment_user_id_array = $row['from'];
									$comment_user_id = $comment_user_id_array['id'];
									$comment = $row['message'];
									fwrite($outputFile,"comment_user_id\t".$comment_user_id."\n");
									fwrite($outputFile,"comment\t".$comment."\n");
								}
								fwrite($outputFile,"Comments_End\n");
							}
							if($action)
							{
								foreach($action as $actionrow)
								{

									fwrite($outputFile,"PostActions\t".$actionrow['name']."\n");
								}
							}
							if($likes)
							{
								fwrite($outputFile, "LikesCount\t".$likes['count']."\n");
				
								$likesRow = $likes['data'];
								if($likesRow)
								{
									fwrite($outputFile,"Likes\t");
									foreach($likesRow as $likesRowData)
									{
										fwrite($outputFile, $likesRowData['id'].",");
									}
									fwrite($outputFile,"\n");	
								}
							}
							fwrite($outputFile,"messageType\t".$messageType."\n");
							fwrite($outputFile,"createdTime\t".$createdTime."\n");
							fwrite($outputFile,"updatedTime\t".$updatedTime."\n");			
							fwrite($outputFile,"******************************************************************************************************\n");
			}
			fclose($outputFile);
		}
		$count = $count - 1;
	}
    ?>
    <?php else: ?>
    <strong><em>You are not Connected.</em></strong>
    <?php endif ?>
    
    <p> I would not be collecting any private data. This application has been designed to collect data that <br />is visible to all your friends on Facebook.
    If you know about this application/site , any data can be <br />manually accessed by us from your facebook profile as friends, as we have only asked our close friends.<br />This is just to help me efficiently 
    gather data and manage it. We wil periodically be removing data from <br />server so that your data does  not stay on server for more than 48 hrs.
    After our project is completed (by May 10, 2011) <br />we will destroying all the data collected permanently.
</p>
    <p>If you encounter any error, please feel free to post on my wall. Your cooperation is appreciated</p>
  </body>
</html>
